package com.authspere.plugin.global;

import com.authsphere.common.enums.ContextHeaderEnum;
import com.authsphere.plugin.api.WebExchange;
import com.authsphere.plugin.api.context.AuthSphereContext;
import com.authsphere.plugin.api.context.AuthSphereContextBuilder;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;

import java.time.LocalDateTime;
import java.util.Optional;

/**
 * @program: AuthSphere
 * @description:
 * @author: YuKai Fan
 * @create: 2025/3/25 16:00
 **/
public class DefaultAuthSphereContextBuilder implements AuthSphereContextBuilder {

    @Override
    public AuthSphereContext build(WebExchange exchange) {
        HttpServletRequest request = exchange.getRequest();
        AuthSphereContext context = buildDefaultContext(request);
        ContextHeaderEnum[] headerEnums = ContextHeaderEnum.values();
        for (ContextHeaderEnum headerEnum : headerEnums) {
            String header = request.getHeader(headerEnum.getHeaderName());
            if (StringUtils.isNotBlank(header)) {
                context.setHeader(headerEnum.getHeaderName(), header);
            }
        }
        return context;
    }

    private AuthSphereContext buildDefaultContext(final HttpServletRequest request) {
        AuthSphereContext context = new AuthSphereContext();
        context.setStartDateTime(LocalDateTime.now());
        context.setPath(request.getRequestURI());
        Optional.ofNullable(request.getMethod()).ifPresent(context::setHttpMethod);
        return context;
    }
}
